<!-- @format -->

<template>
  <div ref="mathContainer" class="math-container">
    <slot></slot>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, onUpdated, ref, watch } from 'vue'

export default defineComponent({
  name: 'MathJaxRenderer',
  props: {
    content: {
      type: String,
      default: ''
    },
    options: {
      type: Object,
      default: () => ({})
    }
  },
  setup(props) {
    const mathContainer = ref<HTMLElement | null>(null)
    
    // 配置MathJax
    const configureMathJax = () => {
      window.MathJax = {
        tex: {
          inlineMath: [['\\(', '\\)']],
          displayMath: [['$$', '$$']],
          packages: ['base', 'ams', 'noerrors', 'noundefined', 'newcommand', 'boldsymbol']
        },
        options: {
          enableMenu: false,
          ...props.options,
          renderActions: {
            addMenu: [0, '', ''],
            checkLoading: [1000, () => '', '']
          }
        },
        startup: {
          pageReady: () => {
            return window.MathJax.startup.defaultPageReady()
          }
        }
      }
    }

    // 渲染MathJax
    const renderMathJax = () => {
      if (window.MathJax && window.MathJax.typesetPromise) {
        window.MathJax.typesetPromise([mathContainer.value])
          .then(() => {
            console.log('MathJax渲染完成')
          })
          .catch((err: any) => {
            console.error('MathJax渲染错误:', err)
          })
      }
    }

    // 加载MathJax
    const loadMathJax = () => {
      if (!window.MathJax) {
        const script = document.createElement('script')
        script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
        script.async = true
        document.head.appendChild(script)
        
        script.onload = () => {
          configureMathJax()
          renderMathJax()
        }
      } else {
        configureMathJax()
        renderMathJax()
      }
    }

    onMounted(() => {
      loadMathJax()
    })

    onUpdated(() => {
      renderMathJax()
    })

    // 监听内容变化，重新渲染
    watch(() => props.content, () => {
      if (mathContainer.value && props.content) {
        mathContainer.value.innerHTML = props.content
        renderMathJax()
      }
    })

    return {
      mathContainer
    }
  }
})
</script>

<!-- <script lang="ts">
declare global {
  interface Window {
    MathJax: any;
  }
}
</script> -->

<style scoped>
.math-container {
  font-family: 'Times New Roman', serif;
  line-height: 1.6;
}
</style>